package com.example.demo3;

import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;


import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private final int UPDATE = 1;
    private final int IMAGELOAD = 2;
    private final int LOCATION = 3;
    private String address = null;
    private SwipeRefreshLayout swipeRefreshLayout;
    private ScrollView scrollView;
    private LinearLayout WeatherReport;
    private TextView city;
    private TextView littleWeather;
    private TextView suggest_label;
    private TextView suggest_text;
    private TextView temp;
    private TextView dot;
    private String imageUrl;
    private ImageView imageView;
    private Handler handler = new Handler();
    private Weather weather = new Weather();
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        imageView = (ImageView) findViewById(R.id.Bingpic);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.Refresh);
        scrollView = (ScrollView) findViewById(R.id.WeatherContent);
        scrollView.setVisibility(View.INVISIBLE);
        WeatherReport = (LinearLayout) findViewById(R.id.Report);
        city = (TextView) findViewById(R.id.city);
        littleWeather = (TextView) findViewById(R.id.littleWeather);
        temp = (TextView) findViewById(R.id.temp);
        dot = (TextView) findViewById(R.id.dot);
        suggest_label = (TextView) findViewById(R.id.suggest_label);
        suggest_text = (TextView) findViewById(R.id.suggest_text);
        initLocation();
        new Thread(new Runnable() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        getImageView();
                    }
                });
            }
        }).start();
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case UPDATE:
                        showReportData();
                        break;
                    case IMAGELOAD:
                        Glide.with(MainActivity.this).load(imageUrl).into(imageView);
                        scrollView.setVisibility(View.VISIBLE);
                        break;
                    case LOCATION:
                        sendRequestWithOkHttp();
                        break;
                }
            }
        };
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.
                OnRefreshListener() {
            @Override
            public void onRefresh() {
                WeatherReport.removeAllViews();
                sendRequestWithOkHttp();
                getImageView();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar, menu);
        return true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mLocationClient.onDestroy();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.ContactAuthor:
                Toast.makeText(this, "作者已失联！", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            default:
                break;
        }
    }

    public void sendRequestWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("https://free-api.heweather.com/v5/weather?city=" + address + "&key=79ca351e36bf4476b74699d1b4c1a73e")
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    parseJSON(responseData);
                    showResponseData();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            swipeRefreshLayout.setRefreshing(false);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void parseJSON(String jsonData) {
        Gson gson = new Gson();
        WeatherBean bean = gson.fromJson(jsonData, WeatherBean.class);
        WeatherBean.HeWeather5Bean beanCase = bean.getHeWeather5().get(0);
        String city = beanCase.getBasic().getCity();
        String temp = beanCase.getNow().getTmp();
        String littleWeather = beanCase.getNow().getCond().getTxt();
        String suggestion = beanCase.getSuggestion().getAir().getTxt() +
                beanCase.getSuggestion().getDrsg().getTxt();
        weather.setCity(city);
        weather.setTemp(temp);
        weather.setLittleWeather(littleWeather);
        weather.setSuggestion(suggestion);
        weather.removeAllReports();
        for (WeatherBean.HeWeather5Bean.DailyForecastBean item :
                beanCase.getDaily_forecast()) {
            Log.d("Main", "parseJSON: ");
            String desc = item.getCond().getTxt_d();
            String max = item.getTmp().getMax();
            String min = item.getTmp().getMin();
            switch (beanCase.getDaily_forecast().indexOf(item)) {
                case 0:
                    weather.addReports("今天", desc, max, min);
                    break;
                case 1:
                    weather.addReports("明天", desc, max, min);
                    break;
                case 2:
                    weather.addReports("后天", desc, max, min);
                    break;
                default:
                    break;
            }
        }
        Message message = new Message();
        message.what = UPDATE;
        handler.sendMessage(message);
    }

    private void showResponseData() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                String cityText = weather.getCity();
                String lw = weather.getLittleWeather();
                String tempText = weather.getTemp();
                String suggestion = "    " + weather.getSuggestion();
                city.setText(cityText);
                temp.setText(tempText);
                littleWeather.setText(lw);
                suggest_text.setText(suggestion);
                Toast.makeText(MainActivity.this, "已获取最新天气"
                        , Toast.LENGTH_SHORT).show();
            }
        });
    }

    //显示天气预报数据
    private void showReportData() {
        for (Weather.WeatherReport report : weather.getReports()) {
            View view = LayoutInflater.from(this).inflate(R.layout.report_item
                    , WeatherReport, false);
            TextView date = (TextView) view.findViewById(R.id.item_date);
            TextView desc = (TextView) view.findViewById(R.id.item_desc);
            TextView temp = (TextView) view.findViewById(R.id.item_temp);
            date.setText(report.getDate());
            desc.setText(report.getDesc());
            temp.setText(report.getMaxTemp() + "/" + report.getMinTemp() + "℃");
            WeatherReport.addView(view);
        }
    }

    public void getImageView() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("http://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1")
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    imageUrl = getImageUrl(responseData);
                    Message message = new Message();
                    message.what = IMAGELOAD;
                    handler.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private String getImageUrl(String jsonData) {
        Gson gson = new Gson();
        BingPicBean bean = gson.fromJson(jsonData, BingPicBean.class);
        BingPicBean.ImagesBean image = bean.getImages().get(0);
        String url = "http://cn.bing.com" + image.getUrl();
        return url;
    }

    public void initLocation() {
        mLocationClient = new AMapLocationClient(this);
        mLocationOption = new AMapLocationClientOption();
        mLocationListener = new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation amapLocation) {
                if (amapLocation != null) {
                    if (amapLocation.getErrorCode() == 0) {
                        mLocationClient.stopLocation();
                        address = amapLocation.getCity();
                        address = address.substring(0, address.length() - 1);
                        Log.d("MainActivity", address);
                        Message message = new Message();
                        message.what = LOCATION;
                        handler.sendMessage(message);
                    } else {
                        Log.e("AmapError", "location Error, ErrCode:"
                                + amapLocation.getErrorCode() + ", errInfo:"
                                + amapLocation.getErrorInfo());
                    }
                }
            }
        };
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(true);
        mLocationOption.setNeedAddress(true);
        mLocationOption.setHttpTimeOut(20000);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();
        mLocationClient.setLocationListener(mLocationListener);
    }

}


